package com.biodiv.community.Interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.biodiv.community.constant.RedisKeys;
import com.biodiv.community.manager.cache.RedisCacheManager;
import com.biodiv.community.threadLocal.UserContext;
import com.biodiv.community.utils.JwtUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;


/**
 * @author tianquan
 */
@Component
@RequiredArgsConstructor
public class TokenInterceptor implements HandlerInterceptor {

    private final RedisCacheManager redisCacheManager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的 Token
        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) {
            sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "未提供 Token");
            return false;
        }

        // 验证并解析 Token
        Long userId = JwtUtils.getUserIdFromToken(token);
        if (ObjectUtil.isNull(userId)) {
            sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "Token无效");
            return false;
        }

        // 查询redis中是否存在该token
        String cacheToken = redisCacheManager.get(RedisKeys.USER_TOKEN_PREFIX + userId, String.class);
        if (ObjectUtil.isNull(cacheToken)) {
            sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "Token过期");
            return false;
        }

        // 检查是否需要刷新Token
        if (JwtUtils.shouldRefreshToken(token)){
            String newToken = JwtUtils.generateToken(userId);
            redisCacheManager.set(RedisKeys.USER_TOKEN_PREFIX + userId, newToken);
            response.setHeader("Authorization", newToken);
        }

        // 将userId 和 sex存入ThreadLocal上下文中
        UserContext.setUserId(userId);
        return true;
    }

    /**
     * 返回带有详细错误信息的响应
     *
     * @param response   HttpServletResponse 对象
     * @param statusCode HTTP 状态码
     * @param message    错误信息
     * @throws Exception 异常
     */
    private void sendErrorResponse(HttpServletResponse response, int statusCode, String message) throws Exception {
        response.setStatus(statusCode);
        response.setContentType("application/json;charset=UTF-8");

        // 构建响应体
        Map<String, Object> errorDetails = new HashMap<>();
        errorDetails.put("status", statusCode);
        errorDetails.put("error", "Unauthorized");
        errorDetails.put("code", String.valueOf(statusCode));
        errorDetails.put("message", message);

        // 写入响应体
        ObjectMapper objectMapper = new ObjectMapper();
        response.getWriter().write(objectMapper.writeValueAsString(errorDetails));
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.clear();
    }
}

